package com.team6.yygh.msm.controller;

import com.team6.yygh.msm.service.MsmService;
import com.team6.yygh.msm.utils.RandomUtil;
import com.team6.yygh.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmApiController
 * @Author ZhuYouWan
 * @Date 2022/10/24 13:39
 **/
@Api(tags = "发送短信验证码")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送手机验证码
     */
    @ApiOperation(value = "发送验证码")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        // 从redis获取验证码，如果获取不到，返回ok
        // key为手机号 value为验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        // 如果从redis获取不到
        // 生成验证码
        code = RandomUtil.getSixBitRandom();
        // 通过整合短信服务进行发送
        boolean isSend = msmService.send(phone, code);
        // 把生成的验证码放入redis中，并设置过期时间
        if (isSend){
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail("验证码发送失败");
        }
    }
}
